package com.example.flower_shop.service.impl;

import com.example.flower_shop.exception.BusinessException;
import com.example.flower_shop.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    private static final Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    @Value("${upload.path}")
    private String uploadPath;

    @Value("${upload.domain}")
    private String domain;

    @Override
    public String uploadImage(MultipartFile file) {
        return uploadImage(file, null);
    }

    @Override
    public String uploadImage(MultipartFile file, String subPath) {
        logger.info("开始上传文件处理...");

        // 检查文件类型
        String contentType = file.getContentType();
        logger.info("文件类型: {}", contentType);
        if (contentType == null || !contentType.startsWith("image/")) {
            logger.error("无效的文件类型: {}", contentType);
            throw new BusinessException("只能上传图片文件");
        }

        // 检查文件大小
        logger.info("文件大小: {} 字节", file.getSize());
        if (file.getSize() > 5 * 1024 * 1024) {
            logger.error("文件过大: {} 字节", file.getSize());
            throw new BusinessException("图片大小不能超过5MB");
        }

        try {
            // 创建上传目录
            Path uploadDir = Paths.get(uploadPath).toAbsolutePath().normalize();
            if (subPath != null && !subPath.isEmpty()) {
                uploadDir = uploadDir.resolve(subPath);
            }
            logger.info("上传目录: {}", uploadDir);

            if (!Files.exists(uploadDir)) {
                Files.createDirectories(uploadDir);
                logger.info("创建上传目录: {}", uploadDir);
            }

            // 生成文件名
            String originalFilename = StringUtils.cleanPath(file.getOriginalFilename());
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = UUID.randomUUID().toString() + extension;

            // 完整的文件路径
            Path targetPath = uploadDir.resolve(filename);
            logger.info("目标文件路径: {}", targetPath);

            // 保存文件
            Files.copy(file.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);
            logger.info("文件保存成功: {}", filename);

            // 返回完整的文件URL
            String fileUrl = domain + "/uploads/images/" +
                    (subPath != null && !subPath.isEmpty() ? subPath + "/" : "") +
                    filename;
            logger.info("文件URL: {}", fileUrl);
            return fileUrl;

        } catch (IOException e) {
            logger.error("文件上传失败", e);
            throw new BusinessException("文件上传失败: " + e.getMessage());
        }
    }
}
